package it.polimi.iol.itilrg.util;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public abstract class DBManager {

	public DBManager() {
	}
	protected EntityManager getEntityManager() {
		return EMF.getEM();
	}

	@SuppressWarnings("unchecked")
	protected List performQuery(String str) {
		Query query = getEntityManager().createQuery(str);
		return query.getResultList();
	}

	protected void deleteObject(Object entity) {
		EntityManager em = getEntityManager();
		
		em.getTransaction().begin();
		try {
			em.remove(entity);
		    em.getTransaction().commit();
		} finally {
		    if (em.getTransaction().isActive()) {
		        em.getTransaction().rollback();
		    }
		}
		
	}

	protected void saveObject(Object entity) {
		EntityManager em = getEntityManager();
		
		em.getTransaction().begin();
		try {
			em.persist(entity);
		    em.getTransaction().commit();
		} finally {
		    if (em.getTransaction().isActive()) {
		        em.getTransaction().rollback();
		    }
		}
		
		
	}

	protected Object getObjectForPK(Class<?> cls, Object id) {
		if (id == null) {
			return null;
		}
		return getEntityManager().find(cls, id);
	}

}
